import Config from '@/utils/config';
import Alert from '@/components/Alert';
import AlertMore from '@/components/AlertMore'
import AlertBottom from '@/components/AlertBottom'
import AlertRank from '@/components/AlertRank'
import callApp from 'lv/Util/callApp';
import { Particle } from "@/utils/animation";
import getLocation from '@/util/getLocation'

export default {
	install(Vue) {
		Vue.prototype.isYangshipin = function () {
			return /yangshipin/i.test(navigator.userAgent);
		};
		/**
		* 创建气泡
		*/
		Vue.prototype.createBubble = function () {
			// let url =
			// "https://sapi.yangshipin.cn/assets/x/other/deepDiving/picture/loading/bubble.png";
			let url = "https://sapi.yangshipin.cn/assets/x/other/deepDiving/static/home/气泡2.png"
			let particle_1 = new Particle();
			particle_1.minX = 0;
			particle_1.maxX = 300;
			particle_1.minY = 20;
			particle_1.maxY = 50;
			particle_1.maxCount = 10;
			particle_1.minLifeTime = 20000;
			particle_1.maxLifeTime = 30000;
			particle_1.minSpeed = 0.8;
			particle_1.maxSpeed = 1.2;
			particle_1.createPartical(url, document.getElementById("loading-bubble"));
			let particle_2 = new Particle();
			particle_2.minX = 0;
			particle_2.maxX = 300;
			particle_2.minY = 300;
			particle_2.maxY = 400;
			particle_2.maxCount = 20;
			particle_2.minLifeTime = 20000;
			particle_2.maxLifeTime = 30000;
			particle_2.minSpeed = 0.6;
			particle_2.maxSpeed = 1.2;
			particle_2.createPartical(url, document.getElementById("loading-bubble"));
			let particle_3 = new Particle();
			particle_3.minX = 0;
			particle_3.maxX = 300;
			particle_3.minY = 500;
			particle_3.maxY = 600;
			particle_3.maxCount = 20;
			particle_3.minLifeTime = 30000;
			particle_3.maxLifeTime = 40000;
			particle_3.minSpeed = 0.6;
			particle_3.maxSpeed = 1.2;
			particle_3.createPartical(url, document.getElementById("loading-bubble"));

			return [particle_1, particle_2, particle_3]
		},

		Vue.prototype.callApp = function (param, href, link) {
			//跳原生视频页
			let url = "cctvvideo://cctv.com/VideoDetailActivity?vid=" + param
			if (href) {
				//跳原生关注页
				if (this.inYspApp()) {
					window.location.href = "cctvvideo://cctv.com/FollowActorPage?dataKey=21238457084818071"
				}
				url = "cctvvideo://cctv.com/FollowActorPage?dataKey=21238457084818071"
			}
			if(link){
				//跳端内h5页面
				let url2 = encodeURIComponent(link)
				console.log("跳端内h5",url2)
				url = `cctvvideo://cctv.com/H5InteractActivity?url=${url2}`
			}
			console.log("点击潜艇", url)
			callApp.action(url);
		};

		Vue.prototype.callAppLive = function (pid) {
			let temp = 'cctvvideo://cctv.com/VideoLiveActivity?pid=' + pid + "&type=1";
			//let url = encodeURIComponent(temp)// `H5InteractActivity?url=${url2}`
			console.log("潜艇直播", temp)
			callApp.action(temp);
		};

		//根据经纬度测算距离
		Vue.prototype.distanceCalc = function (to, callback) {
			getLocation().then(function (value) {
				var radLat1 = to.lat * Math.PI / 180.0;
				var radLat2 = value["latitude"] * Math.PI / 180.0;
				var a = radLat1 - radLat2;
				var b = to.lon * Math.PI / 180.0 - value["longitude"] * Math.PI / 180.0;
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137;// EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000; //输出为公里
				s = s.toFixed(0);
				callback && callback(s)
			})
			// var geolocation = new BMap.Geolocation();
			// geolocation.getCurrentPosition(function (r) {
			// 	//this.map.panTo(r.point);
			// 	if (this.getStatus() == BMAP_STATUS_SUCCESS) {
			// 		console.log(this.getStatus())
			// 		console.log('直接告诉您的位置：' + r.point.lng + ',' + r.point.lat);
			// 		// if (r.accuracy == null) { //用户拒绝地理位置授权
			// 		// 	alert('不告诉我你在哪，怎么带你去深潜呢');
			// 		// 	return;
			// 		// }
			// 		var radLat1 = to.lat * Math.PI / 180.0;
			// 		var radLat2 = r.point.lat * Math.PI / 180.0;
			// 		var a = radLat1 - radLat2;
			// 		var b = to.lon * Math.PI / 180.0 - r.point.lng * Math.PI / 180.0;
			// 		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
			// 			Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
			// 		s = s * 6378.137;// EARTH_RADIUS;
			// 		s = Math.round(s * 10000) / 10000; //输出为公里
			// 		s = s.toFixed(0);
			// 		callback && callback(s)
			// 	}
			// 	else {
			// 		return 'failed' + this.getStatus();
			// 	}
			// }, { enableHighAccuracy: true })
			//关于状态码
			//BMAP_STATUS_SUCCESS	检索成功。对应数值“0”。
			//BMAP_STATUS_CITY_LIST	城市列表。对应数值“1”。
			//BMAP_STATUS_UNKNOWN_LOCATION	位置结果未知。对应数值“2”。
			//BMAP_STATUS_UNKNOWN_ROUTE	导航结果未知。对应数值“3”。
			//BMAP_STATUS_INVALID_KEY	非法密钥。对应数值“4”。
			//BMAP_STATUS_INVALID_REQUEST	非法请求。对应数值“5”。
			//BMAP_STATUS_PERMISSION_DENIED	没有权限。对应数值“6”。(自 1.1 新增)
			//BMAP_STATUS_SERVICE_UNAVAILABLE	服务不可用。对应数值“7”。(自 1.1 新增)
			//BMAP_STATUS_TIMEOUT	超时。对应数值“8”。(自 1.1 新增)
		};

		Vue.prototype.inYspApp = function () {
			if (navigator.userAgent.indexOf("yangshipin") >= 0) {
				return true
			} else {
				return false
			}
		}

		Vue.prototype.clickLink = function (pid, vid, url) {
			//console.log("item ::::: ", pid,vid,url)
			this.onTraceCookies('cvm-click-link');
			if (this.inYspApp()) {
				if (pid) {
					window.location.href = 'cctvvideo://cctv.com/VideoLiveActivity?type=1&pid=' + pid
				} else if (vid) {
					window.location.href = 'cctvvideo://cctv.com/VideoDetailActivity?vid=' + vid
				}

			}
			if (pid) {
				this.callAppLive(pid)
			} else if (vid) {
				this.callApp(vid)
				//this.callApp('//m.yangshipin.cn/video?type=0&vid=' + vid)
				//window.open('//m.yangshipin.cn/video?type=0&vid=' + vid, "_blank")
				// const aTemp = document.createElement("a")
				// aTemp.href = '//m.yangshipin.cn/video?type=0&vid=' + vid;
				// aTemp.target = '_blank'
				// aTemp.click()
				//window.location.href = '//m.yangshipin.cn/video?type=0&vid=' + vid;
			} else if (url) {
				window.location.href = url;
			}
		};

		Vue.prototype.jumpLink = function (url) {
			this.onTraceCookies('cvm-jump-click');
			window.location.href = url;
		};

		Vue.prototype.getTimeByMillisecond = function (millisecond) {
			var second = Math.round(millisecond / 1000);
			var hour = Math.floor(second / 3600);
			var minute = Math.floor((second - hour * 3600) / 60);
			second = second - hour * 3600 - minute * 60;
			if (hour < 10) hour = '0' + hour;
			if (minute < 10) minute = '0' + minute;
			if (second < 10) second = '0' + second;

			return hour + ':' + minute + ':' + second;
		};

		Vue.prototype.createBaiduMap = function () {
			var allMap = document.createElement('div');
			allMap.id = 'allMap';
			allMap.style.width = '800px';
			allMap.style.height = '470px';
			allMap.style.position = 'absolute';
			allMap.style.left = 0;
			allMap.style.top = 0;
			allMap.style.overflow = 'hidden';
			allMap.style.margin = 0;
			document.body.appendChild(allMap);
			// 百度地图API功能
			let map = new BMap.Map('allMap', { minZoom: Config.minZoom, maxZoom: Config.maxZoom, enableMapClick: false });
			let style = [
				{
					featureType: 'land',
					elementType: 'geometry',
					stylers: {
						color: '#faf0e0ff'
					}
				},
				{
					featureType: 'water',
					elementType: 'geometry',
					stylers: {
						color: '#b3d0d2ff'
					}
				}
			];
			map.setMapStyle({ styleJson: style });
			// 所有都默认中心点是北京
			map.centerAndZoom(new BMap.Point(116.404, 39.915), 2);
			map.enableScrollWheelZoom();
			map.enableInertialDragging();
			map.disableContinuousZoom();
			map.disableDoubleClickZoom();
			map.enableDoubleClickZoom();

			return map;
		};

		let half;
		Vue.prototype.createHalf = function (options) {
			if (half) this.deleteHalf();
			var message = Vue.extend(Alert);
			var component = new message({ data: options }).$mount();
			half = component.$el;
			document.body.appendChild(half);
		};

		Vue.prototype.deleteHalf = function () {
			if (half) document.body.removeChild(half);
			half = undefined;
		};

		let createRank;
		Vue.prototype.createRank = function (options) {
			if (createRank) this.deleteRank();
			var message = Vue.extend(AlertRank);
			var component = new message({ data: options }).$mount();
			createRank = component.$el;
			document.body.appendChild(createRank);
		};

		Vue.prototype.deleteRank = function () {
			if (createRank) document.body.removeChild(createRank);
			createRank = undefined;
		};

		let halfMore;
		Vue.prototype.createHalfMore = function (options) {
			if (halfMore) this.deleteHalfMore();
			var message = Vue.extend(AlertMore);
			var component = new message({ data: options }).$mount();
			halfMore = component.$el;
			document.body.appendChild(halfMore);
		};

		Vue.prototype.deleteHalfMore = function () {
			if (halfMore) document.body.removeChild(halfMore);
			halfMore = undefined;
		};

		let halfBottom;
		Vue.prototype.createHalfBottom = function (options) {
			if (halfBottom) this.deleteHalfBottom();
			var message = Vue.extend(AlertBottom);
			var component = new message({ data: options }).$mount();
			halfBottom = component.$el;
			document.body.appendChild(halfBottom);
		};

		Vue.prototype.deleteHalfBottom = function () {
			if (halfBottom) document.body.removeChild(halfBottom);
			halfhalfBottomMore = undefined;
		};

		Vue.prototype.tweenMove = function (id, x, y, time, callback) {
			var element = document.getElementById(id);
			if (!element) {
				console.error('error id:' + id);
				return;
			}
			var startTimestamp = 0;
			var flag = element.style.transform.search(/translate\(/) === -1;
			var originX = flag
				? 0
				: parseFloat(
					element.style.transform
						.match(/translate\((-)?\d+(\.\d+)?px,([ ])?(-)?\d+(\.\d+)?px\)/)
						.toString()
						.match(/(-)?\d+(\.\d+)?px,/)
				);
			var originY = flag
				? 0
				: parseFloat(
					element.style.transform
						.match(/translate\((-)?\d+(\.\d+)?px,([ ])?(-)?\d+(\.\d+)?px\)/)
						.toString()
						.match(/([ ])?(-)?\d+(\.\d+)?px\)/)
				);
			var speedX = time === 0 ? x : x / time;
			var speedY = time === 0 ? y : y / time;
			if (flag)
				element.style.transform = element.style.transform.concat(
					' translate(' + originX + 'px, ' + originY + 'px)'
				);
			var animate = function () {
				requestAnimationFrame(function (delta) {
					if (startTimestamp === 0) startTimestamp = delta;
					var deltaTime = delta - startTimestamp;
					if (deltaTime >= time) {
						element.style.transform = element.style.transform.replace(
							/translate\((-)?\d+(\.\d+)?px,([ ])?(-)?\d+(\.\d+)?px\)/,
							'translate(' + (originX + x) + 'px, ' + (originY + y) + 'px)'
						);
						if (callback) callback();
					} else {
						animate();
						element.style.transform = element.style.transform.replace(
							/translate\((-)?\d+(\.\d+)?px,([ ])?(-)?\d+(\.\d+)?px\)/,
							'translate(' +
							(originX + speedX * deltaTime) +
							'px, ' +
							(originY + speedY * deltaTime) +
							'px)'
						);
					}
				});
			};
			animate();
		};

		Vue.prototype.tweenHeight = function (id, source, target, time, callback) {
			let element = document.getElementById(id);
			if (!element) {
				console.error('error id:' + id);
				return;
			}
			// delta为累积时间,加起始时间戳做差值
			let startTimestamp = 0;
			let result;
			let speed = (target - source) / time;
			let animate = function () {
				requestAnimationFrame(function (delta) {
					if (startTimestamp === 0) startTimestamp = delta;
					result = source + (delta - startTimestamp) * speed;
					if ((result >= target && speed > 0) || (result <= target && speed < 0)) {
						element.style.height = target + '%';
						if (callback) callback();
					} else {
						element.style.height = result + '%';
						animate();
					}
				});
			};
			animate();
		};

		// 追踪指定行为
		Vue.prototype.onTraceCookies = function (name) {
			var $ = window.Zepto;
			// 上报一个动作
			// 上报 faction=action-name
			$(document).trigger('trace', {
				BossId: '8190',
				faction: name
			});
		};
	}
};
